const express = require('express')
const triendRouter = express.Router()
const triendModel = require('../modules/triend_tab')
const userModel = require('../modules/user_tab')
const commentModel = require('../modules/comment_tab')
const triendImgModel = require('../modules/triend_img_tab')
const triendLikeModel = require('../modules/triend_like_tab')
const { body, validationResult } = require('express-validator')
const { raw } = require('body-parser')
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const QueryTypes = Sequelize.QueryTypes


//根据分页、动态内容、发布人、创建时间排序查询所有内容
triendRouter.get('/search', async (req, res, next) => {
  try {
    const page = parseInt(req.query.pageNum) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const offset = (page - 1) * pageSize;

    const nickname = req.query.nickname
    const content = req.query.content
    const sortFieldName = req.query.sortFieldName
    const sortOrder = req.query.sortOrder || 'DESC'
    const order = []
    let where = {
      is_delete: 0
    }
    let users = []
    let userIds = [] //存储用户id的数组
    order.push([sortFieldName, sortOrder])
    if (content) {
      where.content = {
        [Op.like]: `%${content}%`
      }
    }
    if (nickname) {
      //根据昵称去用户表里面模糊查询
      users = await userModel.findAll({
        where: {
          nickname: {
            [Op.like]: `%${nickname}%`
          },
          is_delete: 0
        },
        attributes: ['user_id', 'nickname'] // 选择用户id和昵称
      })
      // 提取用户ID数组
      userIds = users.map(user => user.user_id);
      if (userIds.length > 0) {
        where.user_id = {
          [Op.in]: userIds
        }
      }
    }
    const triends = await triendModel.findAll({
      raw: true,
      offset,
      limit: pageSize,
      order,
      where,
      include: [{
        model: userModel,
        as: 'user_tab',
        attributes: ['nickname'],
        where: { is_delete: 0 },
        required: true
      },
      {
        model: commentModel,
        as: 'triend_comment',
        attributes: [],
        where: { is_delete: 0 },
        required: false,
        separate: true
      },
      {
        model: triendLikeModel,
        as: 'triend_like',
        attributes: [],
        where: { is_delete: 0 },
        required: false,
        separate: true
      },
      ],
      group: ['triend_tab.triend_id'],
      attributes: [
        'triend_id', 'title', 'create_time', 'user_id', 'is_delete', 'content',
        [Sequelize.literal('(SELECT COUNT(*) FROM `comment_tab` WHERE `comment_tab`.`triend_id` = `triend_tab`.`triend_id` AND `comment_tab`.`is_delete` = 0)'), 'triend_comment_count'],
        'user_tab.nickname',
        [Sequelize.literal('(SELECT COUNT(*) FROM `triend_like_tab` WHERE `triend_like_tab`.`triend_id` = `triend_tab`.`triend_id` AND `triend_like_tab`.`is_delete` = 0)'), 'triend_like_count'],
      ]
    })
    res.json({
      code: 1,
      msg: '请求成功',
      total: triends.length,
      data: triends,
    })
  } catch (err) {
    next(err);
  }
})
//根据id删除，假删除
triendRouter.post('/delete/one', async (req, res, next) => {
  try {
    const { triend_id } = req.query;
    const triend = await triendModel.findOne({ where: { triend_id, is_delete: 0 } });
    if (!triend) {
      res.json({
        code: 0,
        msg: '该动态不存在'
      });
      return
    }
    await triend.update({ is_delete: 1 });
    res.json({
      code: 1,
      msg: '请求成功',
    });
  } catch (err) {
    next(err);
  }
})
//批量删除，假删除
triendRouter.post('/delete/amount', async (req, res, next) => {
  try {
    const { triends } = req.query;
    triends.forEach(async (item) => {
      const triend = await triendModel.findOne({ where: { triend_id: item.triend_id, is_delete: 0 } });
      await triend.update({ is_delete: 1 });
    })
    res.json({
      code: 1,
      msg: '请求成功'
    })
  } catch (err) {
    next(err);
  }
})
//根据id查看动态详情
triendRouter.get('/detail', async (req, res, next) => {
  try {
    const { triend_id } = req.query
    //查询当前动态的详情
    const triend = await triendModel.findOne({ where: { triend_id: triend_id, is_delete: 0 } });
    console.log('triend: ', triend);
    //查询用户
    const user = await userModel.findOne({ where: { user_id: triend.user_id, is_delete: 0 } })
    console.log('user: ', user);
    //查询评论
    const comments = await commentModel.findAll({ 
      where: { triend_id: triend_id, is_delete: 0 } ,
      include: [
        {
          model: commentModel, // 关联自己的模型
          as: 'parent_comment', // 使用别名指定子评论
          where: { is_delete: 0 }, // 过滤已删除的子评论
          include: [
            {
              model: commentModel, // 再次关联自己的模型
              as: 'parent_comment' // 使用别名指定父级评论
            }
          ]
        }
      ]
    })
    //查询点赞
    const likes = await triendLikeModel.findAll({
      where: { triend_id: triend_id, is_delete: 0 }, // 指定动态 ID 和未删除的点赞
      include: [{
        model: userModel, // 包含用户模型
        // attributes: ['nickname'], // 选择需要返回的用户昵称字段
        where: { is_delete: 0 }, // 确保用户未被删除
      }],
    });
    console.log('likes: ', likes);

   //查询图片
   const triendImgs = await triendImgModel.findAll({
    raw:true,
    where:{
      is_delete:0,
      triend_id
    },
  })
    res.json({
      code: 1,
      msg: '请求成功',
      data:{
        triend:triend,
        user:user,
        comments:comments,
        likes:likes,
        triendImgs:triendImgs
      }
    })

  } catch (err) {
    next(err);
  }
})
//发布动态
triendRouter.post('/post',async(req,res,next) => {
  try{
    const { create_time,content,title,user_id,imgs } = req.body
      const triends = await triendModel.findAll({raw:true})
      const triend_id = triends.length > 0 ? triends.sort((a, b) => b.triend_id - a.triend_id)[0].triend_id + 1 : 1
      const result1 = triendModel.create({
        triend_id,
        content,
        title,
        user_id,
        create_time
      })
      imgs.forEach(async(item,index) => {
        const imgAll = await triendImgModel.findAll({raw:true})
        const triend_img_id = imgAll.length>0?imgAll.sort((a,b) => b.triend_img_id - a.triend_img_id)[0].triend_img_id + 1 : 1
        const result2 = await triendImgModel.create({
          triend_img_id:triend_img_id + index,
          img:item,
          triend_id:triend_id
        })
      })
      res.json({
        code:1,
        msg:'请求成功'
      })
  }catch(err){
    next(err)
  }
})
//随机动态
triendRouter.get('/random',async(req,res,next) => {
  try{
    const triends = await triendModel.findAll({ raw: true ,
      where:{
        is_delete:0
      },
      include: [
        {
          model: commentModel,
          as: 'triend_comment',
          attributes: [],
          where: { is_delete: 0 },
          required: false,
          separate: true
        },
        {
          model: triendLikeModel,
          as: 'triend_like',
          attributes: [],
          where: { is_delete: 0 },
          required: false,
          separate: true
        },
        ],
        group: ['triend_tab.triend_id'],
        attributes: [
          'triend_id', 'title', 'create_time', 'user_id', 'is_delete', 'content',
          [Sequelize.literal('(SELECT COUNT(*) FROM `comment_tab` WHERE `comment_tab`.`triend_id` = `triend_tab`.`triend_id` AND `comment_tab`.`is_delete` = 0)'), 'triend_comment_count'],
          [Sequelize.literal('(SELECT COUNT(*) FROM `triend_like_tab` WHERE `triend_like_tab`.`triend_id` = `triend_tab`.`triend_id` AND `triend_like_tab`.`is_delete` = 0)'), 'triend_like_count'],
        ]
    })
    const randomIndex = Math.floor(Math.random() * triends.length)
    const triend = triends[randomIndex]
    const triendImgs = await triendImgModel.findAll({
      raw:true,
      where:{
        is_delete:0,
        triend_id:triend.triend_id
      },
     
    })
    const user = await userModel.findOne({
      raw:true,
      where:{
        user_id:triend.user_id,
        is_delete:0
      }
    })
    res.json({
      code:1,
      msg:'请求成功',
      data:{
        ...triend,
        triendImgs,
        ...user
      }
    })
  }catch(err){
    next(err)
  }
})
//点击点赞
triendRouter.post('/like',async(req,res,next) => {
  try{
    const { user_id,triend_id,triend_like_time} = req.body
    const likeAll = await triendLikeModel.findAll({raw:true})
    const like_id = likeAll.length>0? likeAll.sort((a, b) => b.like_id - a.like_id)[0].like_id + 1  : 1
    const like = await triendLikeModel.create({
      like_id,
      user_id,
      triend_id,
      triend_like_time
    })
    //查询当前动态的所有的点赞数
    const num = await triendLikeModel.findAll({
      raw:true,
      where:{
        triend_id,
        is_delete:0
      }
    })
    res.json({
      code:1,
      msg:'请求成功',
      data:{
        number:num.length,
        like
      }
    })
  }catch(err){
    next(err)
  }
})
// 错误处理中间件
triendRouter.use((err, req, res, next) => {

  res.status(500).json({
    code: 0,
    msg: '服务器内部错误',
  });
});
module.exports = triendRouter
